package com.klondike.common.concurrent;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.CountDownLatch;

public class ConcurrentTestHelper {

    public static void executeInSeparateThread(Runnable runnable) throws InterruptedException {
        executeInSeparateThread(runnable, true, null);
    }

    public static void executeInSeparateThread(final Runnable runnable, boolean waitUntilDone,
            UncaughtExceptionHandler uncaughtExceptionHandler) throws InterruptedException {
        final CountDownLatch signal = new CountDownLatch(1);
        Thread t = new Thread() {
            @Override
            public void run() {
                signal.countDown();
                runnable.run();
            }
        };
        t.setUncaughtExceptionHandler(uncaughtExceptionHandler);
        t.start();

        if (waitUntilDone) {
            t.join();
        } else {
            signal.await();
        }
    }

    public static void executeInSeparateThread(Runnable runnable, UncaughtExceptionHandler uncaughtExceptionHandler)
            throws InterruptedException {
        executeInSeparateThread(runnable, true, uncaughtExceptionHandler);
    }

}
